package com.celesea.auth.user.v1.controller;

import com.celesea.auth.dept.service.DeptService;
import com.celesea.auth.role.entity.RoleCode;
import com.celesea.auth.user.entity.User;
import com.celesea.auth.user.service.UserService;
import com.celesea.auth.user.v1.controller.request.PageRequest;
import com.celesea.auth.user.v1.controller.request.PostRequest;
import com.celesea.auth.user.v1.controller.request.PutRequest;
import com.celesea.auth.user.v1.controller.resource.FormResource;
import com.celesea.auth.user.v1.controller.resource.PageResource;
import com.celesea.auth.user.vo.UserFilter;
import com.celesea.auth.user.vo.UserVo;
import com.celesea.framework.util.Page;
import com.celesea.framework.util.PageData;
import com.celesea.framework.util.Sort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author JackYuan
 * @create 2017-10-30 23:01
 */
@RestController
@RequestMapping("v1/users")
@Api(tags = "用户接口")
@PreAuthorize("hasAnyAuthority('" + RoleCode.ADMIN_SYSTEM + "','" + RoleCode.ADMIN_BUS + "')")
public class UserController {
    @Autowired
    public UserService userService;
    @Autowired
    private DeptService deptService;

    @GetMapping
    @ApiOperation(value = "用户分页")
    public PageData<PageResource> page(@Valid PageRequest request, Page page, Sort sort) {
        UserFilter userFilter = new UserFilter(request);
        PageData<User> pageData = userService.selectPage(userFilter, page, sort);
        return pageData.convert(item -> new PageResource(item));
    }

    @PostMapping
    @ApiOperation(value = "保存用户")
    public FormResource post(@RequestBody @Valid PostRequest request) {
        UserVo user = userService.insert(new UserVo(request));
        return new FormResource(user);
    }

    @PutMapping
    @ApiOperation(value = "更新用户")
    public FormResource put(@RequestBody @Valid PutRequest request) {
        UserVo user = userService.update(new UserVo(request));
        return new FormResource(user);
    }

    @GetMapping(value = "/{id}")
    @ApiOperation(value = "根据id查询用户")
    public FormResource get(@PathVariable String id) {
        UserVo user = userService.selectById(id);
        return new FormResource(user);
    }

    @DeleteMapping(value = "/{id}")
    @ApiOperation(value = "根据id删除用户")
    public void delete(@PathVariable String id) {
        userService.doDelete(id);
    }
}
